#coding=utf-8
#LightCam 日志监控程序
#init by hfh 20150212

import multiprocessing,subprocess
import socket,os,time,re,traceback,sys
import lc_libs

def func(agent_hostname,filename,keyword,interval,severity,schedule,holiday):
	file=open(filename,'r')
	file.readlines()
	
	Node=agent_hostname
	AlertGroup="MonitorLogFile"
	AlertKey=filename
	
	while True:
		try:
			#判断时间策略
			tempflags=lc_libs.lc_schedule(schedule)
			if tempflags==False:
				time.sleep(int(interval))
				continue
			#判断节假日
			holiday_state=0
			if int(holiday)==1:
				if lc_libs.lc_isholiday():
					holiday_state=1
			if holiday_state==1:
				time.sleep(int(interval))
				continue
			#执行日志监控
			filecontent=file.readline()
			if "LightCam" in filecontent:
				continue
			if str(filecontent) == "":
				time.sleep(1)
				continue
			for i in keyword.split('|'):
				if i in filecontent:
					AlertKey=filename+"-"+str(i)
					Severity=severity
					Type="1"
					#Summary=filecontent
					Summary=agent_hostname+"日志"+filename+"出现错误信息:"+filecontent
					strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
					print strs
					db.update_eventsdb_rt(events_table,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
					#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					#logfile.write(logdate+" "+strs+"\n")
					#logfile.flush()
				else:
					Severity="1"
					Type="2"
					#Summary=filecontent
					Summary=agent_hostname+"日志"+filename+"出现正常信息:"+filecontent
					strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
					print strs
					#db.update_eventsdb(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
					#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
					#logfile.write(logdate+" "+strs+"\n")
					#logfile.flush()
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
			time.sleep(1)
		#等待
		time.sleep(int(interval))

if __name__ == "__main__":

	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	pool = multiprocessing.Pool(processes=1)
	result = []
	
	#初始化events数据库
	#dbfile="../db/lc_events.db"
	#tablename="lc_events"
	#tablefield="Node varchar(32),AlertGroup varchar(64),AlertKey varchar(64),Severity varchar(8),Type varchar(8),LastOccurrence varchar(32),Summary varchar(256)"
	#db=lc_libs.lc_dboperater(dbfile,tablename,tablefield)
	#db.create_db()
	#db.close_db()

	try:
		#初始化数据库
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		events_dbname='lc_events'
		events_tablename='lc_events'
		
		history_dbname='lc_history'
		history_tablename="lc_logfile"
		
		events_db=db.useDatabase(events_dbname)
		events_table=db.UseCollection(events_db,events_tablename)
		
		history_db=db.useDatabase(history_dbname)
		history_table=db.UseCollection(history_db,history_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)

	for line in open(confname):
		#if line[0] == '#' or agent_hostname != line.split("\t")[0]:
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		filename=line.strip('\n\r').split('\t')[1]
		keyword=line.strip('\n\r').split("\t")[2]
		interval=line.strip('\n\r').split("\t")[3]
		severity=line.strip('\n\r').split("\t")[4]
		schedule=line.strip('\n\r').split("\t")[5]
		holiday=line.strip('\n\r').split("\t")[6]

		pool = multiprocessing.Pool(processes=1)
		result.append(pool.apply_async(func, (agent_hostname,filename,keyword,interval,severity,schedule,holiday)))
			
	pool.close()
	pool.join()
	print result
